package com.alibaba.csp.sentinel.dashboard.rule.nacos.gateway.flow;

import com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.GatewayFlowRuleEntity;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisher;
import com.alibaba.csp.sentinel.dashboard.rule.nacos.NacosConfigUtil;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.util.AssertUtil;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.ConfigType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.List;

@Component("gatewayFlowRulePublish")
public class GatewayFlowRulePublish implements DynamicRulePublisher<List<GatewayFlowRuleEntity>> {
    private static final Logger LOGGER = LoggerFactory.getLogger(GatewayFlowRulePublish.class);
    private final Converter<List<GatewayFlowRuleEntity>, String> converter;
    private final ConfigService configService;

    public GatewayFlowRulePublish(Converter<List<GatewayFlowRuleEntity>, String> converter, ConfigService configService) {
        this.converter = converter;
        this.configService = configService;
    }

    @Override
    public void publish(String app, List<GatewayFlowRuleEntity> rules) throws Exception {
        AssertUtil.notEmpty(app, "app name cannot be empty");
        if (rules == null) {
            return;
        }
        String convertedRule = converter.convert(rules);

        LOGGER.info("sentinel dashboard publisher gateway flow rules : {}", convertedRule);
        configService.publishConfig(app + NacosConfigUtil.GATEWAY_FLOW_DATA_ID_POSTFIX, NacosConfigUtil.GROUP_ID, convertedRule, ConfigType.JSON.getType());
    }
}
